﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Collections;
using System.IO;

namespace GIFT_SHOP_MVC.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        Models.GiftShop_LinQDataContext data = new Models.GiftShop_LinQDataContext();

        public ActionResult Index()
        {
            if (Session["user"] == null)
                return RedirectToAction("Index", "Home");
            else
            {
                Models.User user = (Models.User)Session["user"];
                if (user.Admin == false)
                    return RedirectToAction("Index", "Home");
            }
            return View();
        }

        public ActionResult Navigation()
        {
            return View();
        }

        public ActionResult Search(string query)
        {
            var listproduct = data.SanPhams.Where(p => p.TenSanPham.Contains(query));
            ViewData["title"] = "Search Result";
            return View("ShowProduct", listproduct);
        }

        public ActionResult GetProductByIdCategory(int id)
        {
            var category = data.TheLoais.Single(tl => tl.MaTheLoai == id);
            ViewData["title"] = category.TenTheLoai;
            var listproduct = data.GetProductByIdCategory(id);
            return View("ShowProduct", listproduct);
        }

        public ActionResult Product()
        {
            Session["url"] = "../Admin/Product";
            ViewData["title"] = "All Product";
            var listproduct = data.GetProduct();
            return View("ShowProduct", listproduct);
        }

        public ActionResult Category()
        {
            Session["url"] = "../Admin/Category";
            var listcategories = data.GetCategories();
            return View(listcategories);
        }

        [HttpPost]
        public ActionResult AddCategory(string catename)
        {
            if (catename == "")
                return Redirect(Request.UrlReferrer.ToString());

            Models.TheLoai cate = new Models.TheLoai();
            cate.TenTheLoai = catename;
            cate.Ma_TT = 1;
            data.TheLoais.InsertOnSubmit(cate);
            data.SubmitChanges();
            return RedirectToAction("Category");

        }

        [HttpPost]
        public ActionResult EditCategory(int id, string catename, int status)
        {
            if (catename == "")
                return Redirect(Request.UrlReferrer.ToString());

            Models.TheLoai cate = data.TheLoais.Single(tl => tl.MaTheLoai == id);
            cate.TenTheLoai = catename;
            cate.Ma_TT = status;
            data.SubmitChanges();
            return RedirectToAction("Category");

        }

        public ActionResult FormCategory(int id)
        {
            if (id == 0)
            {
                ViewData["flag"] = "0";
                return View();
            }
            else
            {
                ViewData["flag"] = "1";
                var category = data.TheLoais.Single(tl => tl.MaTheLoai == id);
                var statuscategory = data.TinhTrang_TLs.ToList();
                ViewData["sttcategory"] = new SelectList(statuscategory, "Ma_TT", "Ten", category.Ma_TT);
                return View(category);
            }

        }

        public ActionResult Supplier()
        {
            Session["url"] = "../Admin/Supplier";
            var listsupplier = data.GetSuppliers();
            return View(listsupplier);
        }

        public ActionResult AddSupplier(string supname)
        {
            if (supname == "")
                return Redirect(Request.UrlReferrer.ToString());

            Models.NhaCungCap supplier = new Models.NhaCungCap();
            supplier.TenNhaCungCap = supname;
            supplier.Ma_TT = 1;
            data.NhaCungCaps.InsertOnSubmit(supplier);
            data.SubmitChanges();
            return RedirectToAction("Supplier");

        }

        public ActionResult EditSupplier(int id, string supname, int status)
        {
            if (supname == "")
                return Redirect(Request.UrlReferrer.ToString());

            Models.NhaCungCap supplier = data.NhaCungCaps.Single(sup => sup.MaNhaCungCap == id);
            supplier.TenNhaCungCap = supname;
            supplier.Ma_TT = status;
            data.SubmitChanges();
            return RedirectToAction("Supplier");
        }

        public ActionResult FormSupplier(int id)
        {
            if (id == 0)
            {
                ViewData["flag"] = "0";
                return View();
            }
            else
            {
                ViewData["flag"] = "1";
                var supplier = data.NhaCungCaps.Single(sup => sup.MaNhaCungCap == id);
                var statussup = data.TinhTrang_NhaCungCaps.ToList();
                ViewData["sttsup"] = new SelectList(statussup, "Ma_TT", "Ten", supplier.Ma_TT);
                return View(supplier);
            }
        }

        public ActionResult AddProduct()
        {
            List<Models.SanPham> arrProduct = (List<Models.SanPham>)Session["table"];

            arrProduct = arrProduct.OrderBy(a => a.MaNhaCungCap).ToList();

            int sup_id = -1;
            foreach (Models.SanPham product in arrProduct)
            {
                if (sup_id != product.MaNhaCungCap)
                {
                    sup_id = product.MaNhaCungCap;

                    var import = new Models.PhieuNhap();
                    import.MaNhaCungCap = sup_id;
                    import.TongTien = 0;
                    import.NgayNhap = DateTime.Today;
                    data.PhieuNhaps.InsertOnSubmit(import);
                    data.SubmitChanges();

                    foreach (Models.SanPham pro in arrProduct.Where
                        (p => p.MaNhaCungCap == sup_id))
                    {
                        if (pro.MaSanPham == 0)
                            data.SanPhams.InsertOnSubmit(pro);
                        else
                        {
                            Models.SanPham availPro = data.SanPhams.Single
                                (p => p.MaSanPham == pro.MaSanPham);
                            availPro.SL_Ton = availPro.SL_Ton + pro.SL_Ton;
                            availPro.Gia = pro.Gia;
                            availPro.Ma_TT = pro.Ma_TT;
                        }
                        data.SubmitChanges();

                        Models.CT_PhieuNhap detail = new Models.CT_PhieuNhap();
                        detail.MaSanPham = pro.MaSanPham;
                        detail.SoLuongNhap = pro.SL_Ton;
                        detail.MaPhieuNhap = import.MaPhieuNhap;
                        detail.Gia = pro.SL_Ton;
                        data.CT_PhieuNhaps.InsertOnSubmit(detail);
                        import.TongTien = import.TongTien + (pro.SL_Ton * pro.Gia);
                        data.SubmitChanges();
                    }
                }
            }
            Session["table"] = null;
            return RedirectToAction("Product");
        }

        public ActionResult EditProduct(int id)
        {
            var product = data.GetProductById(id);
            ViewData.Model = product;
            Session["img"] = product.Hinh;
            return View();
        }

        [HttpPost]
        public ActionResult EditProduct(Models.SanPham product, HttpPostedFileBase image)
        {
            if (!ModelState.IsValid)
                return View(product);
            Models.SanPham availproduct = data.SanPhams.Single(p => p.MaSanPham == product.MaSanPham);
            availproduct.TenSanPham = product.TenSanPham;
            availproduct.MaTheLoai = product.MaTheLoai;
            availproduct.MaNhaCungCap = product.MaNhaCungCap;
            availproduct.MoTa = product.MoTa;
            availproduct.Gia = product.Gia;
            availproduct.Ma_TT = product.Ma_TT;
            if (availproduct.Hinh != product.Hinh)
            {
                var fileName = Path.GetFileName(image.FileName);
                var path = Path.Combine(Server.MapPath("~/Image_Product"), fileName);
                image.SaveAs(path);
            }
            
            availproduct.Hinh = product.Hinh;
            data.SubmitChanges();

            return Redirect(Session["url"].ToString());
        }

        public ActionResult FormProduct(int id)
        {
            Session["url"] = "../Admin/FormProduct/1";
            Session["type"] = id;
            return View();
        }

        public ActionResult Detail(int id)
        {
            ViewData.Model = data.GetProductById(id);
            return View();
        }

        public ActionResult DeleteTable(int id)
        {
            if (id == -1)
                Session["table"] = null;
            else
            {
                List<Models.SanPham> arrProduct = (List<Models.SanPham>)Session["table"];
                arrProduct.RemoveAt(id);
                if (arrProduct.Count == 0)
                    Session["table"] = null;
                else
                    Session["table"] = arrProduct;
            }

            return View("FormProduct");
        }

        [HttpPost]
        public ActionResult AddTable(Models.SanPham newproduct, HttpPostedFileBase Hinh)
        {
            if (!ModelState.IsValid)
            {
                return View("FormProduct");
            }
            else
            {
                List<Models.SanPham> arrProduct = new List<Models.SanPham>();

                if (newproduct.MaSanPham == 0)
                {
                    newproduct.Ma_TT = 1;
                    newproduct.SL_Ban = 0;
                    newproduct.SoLuotXem = 0;
                    newproduct.NgayNhap = DateTime.Today;

                    var fileName = Path.GetFileName(Hinh.FileName);
                    var path = Path.Combine(Server.MapPath("~/Image_Product"), fileName);
                    newproduct.Hinh = "../../Image_Product/" + fileName;
                    Hinh.SaveAs(path);
                }
                else
                {
                    var avail_product = data.SanPhams.Single(p => p.MaSanPham == newproduct.MaSanPham);
                    newproduct.TenSanPham = avail_product.TenSanPham;
                    newproduct.MaTheLoai = avail_product.MaTheLoai;
                    newproduct.MaNhaCungCap = avail_product.MaNhaCungCap;
                    newproduct.Hinh = avail_product.Hinh;
                    newproduct.MoTa = avail_product.MoTa;
                    newproduct.Ma_TT = 1;
                }

                if (Session["table"] == null)
                {
                    arrProduct.Add(newproduct);
                    Session["table"] = arrProduct;
                }
                else
                {
                    arrProduct = (List<Models.SanPham>)Session["table"];
                    arrProduct.Add(newproduct);
                    Session["table"] = arrProduct;
                }
                return View("FormProduct");
            }
        }

        public ActionResult ShowTable()
        {
            return View();
        }

        public ActionResult Import()
        {
            Session["url"] = "../Admin/Import";
            return View();
        }

        public ActionResult ShowImports()
        {
            var listimport = data.GetImports();
            return View(listimport);
        }

        public ActionResult ShowImportDetail(int id)
        {
            var lstImportDetail = data.GetImportById(id);
            return View(lstImportDetail);
        }

        public ActionResult Bill()
        {
            Session["url"] = "../Admin/Bill";
            return View();
        }

        public ActionResult ShowBill()
        {
            var listBill = data.GetBill();
            return View(listBill);
        }

        public ActionResult ShowBillDetail(int id)
        {
            var listBillDetail = data.GetBillById(id);
            return View(listBillDetail);
        }

        public ActionResult Export(int id)
        {
            var bill = data.GetBill().Single(b=>b.MaPhieuXuat == id);
            bill.Ma_TT = 2;
            bill.NgayXuat = DateTime.Now;
            data.SubmitChanges();
            return RedirectToAction("ShowBill");
        }

        public ActionResult Users()
        {
            Session["url"] = "../Admin/Users";
            return View();
        }

        public ActionResult ShowUser()
        {
            var listuser = data.GetUsers();
            return View(listuser);
        }

        public ActionResult EditUser(int id)
        {
            ViewData.Model = data.GetUserById(id);
            Session["checkuser"] = true;
            return View();
        }

        [HttpPost]
        public ActionResult EditUser(Models.User user)
        {
            if (!ModelState.IsValid)
                return View();

            Session["checkuser"] = true;
            var us = data.Users.Where(u => (u.UserName == user.UserName && u.MaUser != user.MaUser)).ToList();
            if (us.Any())
            {
                Session["checkuser"] = false;
                return View();
            }
            var avaius = data.Users.Single(u => u.MaUser == user.MaUser);
            avaius.HoTen = user.HoTen;
            avaius.UserName = user.UserName;
            avaius.DiaChi = user.DiaChi;
            avaius.DienThoai = user.DienThoai;
            avaius.Ma_TT = user.Ma_TT;
            data.SubmitChanges();
            return View();
        }

        public ActionResult Report()
        {
            return View();
        }
    }
}
